package client.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;

import messages.MessageAllocateTestId;
import messages.MessageQuestionBySubject;
import messages.MessageSaveQuestionsTest;
import messages.MessageSubject;

import sharedspace.Question;
import sharedspace.QuestionInTest;
import sharedspace.Subject;
import sharedspace.Teacher;
import sharedspace.Test;
import sharedspace.User;
import java.awt.TextField;
import java.awt.SystemColor;
/**
 * This JPnel is a panel for teacher to create a test
 * @author Amir S.
 * @author Jacob C.
 * @author Maya G.
 * @author Michael V.
 */
public class GUI_CreateTest extends JPanel  {
	private static final long serialVersionUID = 1L;
	private static final ArrayList<Question> NULL = null;
	public JTable table;
	public JTable testTabel;
	private JPanel panelQuestion;
	private JPanel panelTest;
	private JScrollPane scrollPaneTable;
	private ArrayList<sharedspace.Question> q;
	private int rowInTable=0;
	public JButton btnAddQ;
	public JButton btnDelete;
	private TextArea txtCommentTeacher;
	private TextArea txtCommentStudent;
	public TextField txtPoints;
	public TextField totalPoints;
	protected User user=null;
	protected Client_GUI MS=null;
	protected String subjectID;
	protected String courseID;
	public JButton btnBack = null;
	private ArrayList<Question> myArrayq;
	private ArrayList<QuestionInTest> myArrayt;
	private JButton btnClear;
	private JButton btnSubmit;
	private Test test;
	private Test testDummy;
	private Subject subject;
	
	public GUI_CreateTest() {
		super();
		this.initialize();
		test = new Test();
		testDummy = new Test();
	}// end constructor
	
	public GUI_CreateTest(Client_GUI ms,User user,String subjectChoosen,String courseChoosen,Subject subject) {
		super();
		this.subjectID=subjectChoosen;
		this.courseID=courseChoosen;
		this.initialize();
		this.user = user;
		this.subject=subject;
		this.MS=ms;
		getQuestiontoChoose();	 
	}// end constructor
	
	public void initialize(){
		
	this.setSize(1000, 700);	
	this.setLayout(null);
	btnBack = new JButton();
	btnBack.setText("Back");
	btnBack.setFont(new Font("Arial", Font.PLAIN, 16));
	btnBack.setBounds(new Rectangle(76, 612, 107, 30));
	btnBack.setVisible(true);
	this.add(btnBack);
		
	btnAddQ = new JButton();	
	btnAddQ.setText("Add Question");
	btnAddQ.setFont(new Font("Arial", Font.PLAIN, 16));
	btnAddQ.setBounds(new Rectangle(645, 236, 140, 30));
	btnAddQ.setVisible(true);
	this.add(btnAddQ);
	btnAddQ.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent arg0) {
			JoinQuestionToTable(table.getSelectedRow());
		}
	});
	
	btnDelete = new JButton();	
	btnDelete.setText("Delete Question");
	btnDelete.setFont(new Font("Arial", Font.PLAIN, 16));
	btnDelete.setBounds(new Rectangle(620, 560, 162, 30));
	btnDelete.setVisible(true);
	this.add(btnDelete);
	btnDelete.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent arg0) {
			if (testTabel.getSelectedRow()!=-1){
			RemoveQuestionFromTable(testTabel.getSelectedRow());}
			else showMessage("Error you didnt choose any question in test", "choose questions in test", JOptionPane.WARNING_MESSAGE);
		}
	});
	
	btnSubmit = new JButton();	
	btnSubmit.setText("Save&Submit test");
	btnSubmit.setFont(new Font("Arial", Font.PLAIN, 16));
	btnSubmit.setBounds(new Rectangle(221, 612, 162, 30));
	btnSubmit.setVisible(true);
	this.add(btnSubmit);
	btnSubmit.addActionListener(new ActionListener() {
		
		public void actionPerformed(ActionEvent arg0) {
			
			if (myArrayt.size()!=0){
				int TotalPoints=0;
				
				for(int i=0;i<myArrayt.size();i++)
				{
				 TotalPoints+=myArrayt.get(i).getPointQuestion();	
						
				}//end for
				if (Integer.parseInt(totalPoints.getText())==100){ // total points is correct
				
				String duration = JOptionPane.showInputDialog("please,Insert Duration of test(minutes):");
				try
				{

				if (cheackDuration(duration))
						{
							createTheTest();
							showMessage("Information, your test is save", "Test Save", JOptionPane.INFORMATION_MESSAGE);
							MS.setContentPane(MS.tchr);
						}
					else JOptionPane.showMessageDialog(null,"Error, invaid number of minutes");
				
				}
				catch(NumberFormatException e)
				{
					JOptionPane.showMessageDialog(null, "Invalid Input");
				}
				
				}else 	showMessage("Error,Incorrect number of Points it needs to be 100", "Total Points in question ", JOptionPane.WARNING_MESSAGE);
		}else
			showMessage("Error you didnt choose any question in test", "choose questions in test", JOptionPane.WARNING_MESSAGE);
		}
	});
	
	btnClear = new JButton();	
	btnClear.setText("Clear Comments");
	btnClear.setFont(new Font("Arial", Font.PLAIN, 16));
	btnClear.setBounds(new Rectangle(828, 337, 162, 30));
	btnClear.setVisible(true);
	this.add(btnClear);
	btnClear.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent arg0) {
			ClearComment();
		}
	});
	
	JLabel title=new JLabel("Create Test");
	title.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 24));
	title.setBounds(new Rectangle(343, 46, 140, 59));
	title.setForeground(Color.BLUE);
	this.add(title);
	
	JLabel lblYourTest = new JLabel("Your Test:");
	lblYourTest.setForeground(SystemColor.desktop);
	lblYourTest.setFont(new Font("Tahoma", Font.BOLD, 16));
	lblYourTest.setBounds(new Rectangle(180, 413, 94, 20));
	add(lblYourTest);

	
	panelQuestion = new JPanel();
	panelQuestion.setBorder(null);
	panelQuestion.setBounds(new Rectangle(145, 115, 670, 110));
	add(panelQuestion, BorderLayout.CENTER);
	panelQuestion.setLayout(new BorderLayout(0, 0));
	
	panelTest = new JPanel();
	panelTest.setBorder(null);
	panelTest.setBounds(new Rectangle(161, 438, 621, 110));
	add(panelTest, BorderLayout.CENTER);
	panelTest.setLayout(new BorderLayout(0, 0));
	
	txtCommentTeacher = new TextArea(100,20);
	txtCommentTeacher.setBounds(424, 337, 376, 67);
	txtCommentTeacher.setText("");
	add(txtCommentTeacher);
	JLabel lblCTacher = new JLabel("Fill Comment for teacher \r\n(visable to you...):");
	lblCTacher.setFont(new Font("Tahoma", Font.PLAIN, 14));
	lblCTacher.setBounds(474, 301, 283, 30);
	add(lblCTacher);
	
	txtCommentStudent = new TextArea(100,20);
	txtCommentStudent.setBounds(86, 337, 310, 67);
	txtCommentStudent.setText("");
	add(txtCommentStudent);
	JLabel lblCStudent = new JLabel("Fill Comment for Student (visable to student):");
	lblCStudent.setFont(new Font("Tahoma", Font.PLAIN, 14));
	lblCStudent.setBounds(87, 299, 296, 30);
	add(lblCStudent);
	
	txtPoints = new TextField();
	txtPoints.setBounds(358, 246, 100, 20);
	
	txtCommentStudent.setText("");
	add(txtPoints);
	JLabel lblPoints = new JLabel("Enter number of Points for Quesion:");
	lblPoints.setFont(new Font("Tahoma", Font.BOLD, 14));
	lblPoints.setBounds(86, 236, 262, 30);
	add(lblPoints);
	
	
	totalPoints= new TextField();
	totalPoints.setEditable(false);
	totalPoints.setBounds(237, 570, 100, 20);
	totalPoints.setFont(new Font("Tahoma", Font.BOLD, 16));
	add(totalPoints);
	JLabel lblTPoint = new JLabel("Total number of points");
	lblTPoint.setFont(new Font("Tahoma", Font.BOLD, 14));
	lblTPoint.setBounds(57, 570, 174, 20);
	add(lblTPoint);
	
	GUI_ImagePanel background =new GUI_ImagePanel(new ImageIcon("images/background1.jpg").getImage());
	background.setLocation(10, 24);
	background.setSize(new Dimension(1140, 800));
	this.add(background);
	}//initialize
	


	/**
	 * this method gets an ArrayList<Question> and fills a table with all question in the subject
	 * @param confirmationAL
	 */
	public void populateTable(ArrayList<Question> questionSelect) {
		String columnNames[] = {"Question ID","Question","Answer 1","Answer 2","Answer 3","Answer 4","correct Answer","Question Instructions"};

		int rows = questionSelect.size();
		String tableModel[][] = new String[rows][columnNames.length];
		for (int i=0; i<rows; i++){
			tableModel[i][0] = questionSelect.get(i).getQuestionID();
			tableModel[i][1] = questionSelect.get(i).getQuestion();
			tableModel[i][2] = questionSelect.get(i).getAnswers()[0];
			tableModel[i][3] = questionSelect.get(i).getAnswers()[1];
			tableModel[i][4] = questionSelect.get(i).getAnswers()[2];
			tableModel[i][5] = questionSelect.get(i).getAnswers()[3];
			tableModel[i][6] = ((Object)questionSelect.get(i).getCorrectAnswer()).toString();
			tableModel[i][7] = questionSelect.get(i).getQuestionCommet();
			}// end for
		


		
		table = new JTable(tableModel, columnNames){
			   public boolean isCellEditable(int rowIndex, int colIndex) {
			   return false; //Disallow the editing of any cell
			   }
			   };
		table.setFont(new Font("Tahoma", Font.PLAIN, 14));
		TableColumn columnCorrect=table.getColumnModel().getColumn(6);
		columnCorrect.setPreferredWidth(WIDTH*100);
		TableColumn columnInst=table.getColumnModel().getColumn(7);
		columnInst.setPreferredWidth(WIDTH*120);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		table.getTableHeader().setReorderingAllowed(false);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		JScrollPane scrollPane= new JScrollPane(table);
		panelQuestion.add(scrollPane);
		table.setName("Questions in Test");
		panelQuestion.setVisible(true);
		
		
	}//end of populatedTable
	
	public void getQuestiontoChoose(){
		
		MessageQuestionBySubject qTc = new MessageQuestionBySubject(subjectID);
		try{
			MS.client.sendToServer(qTc);// get list of teacher subject
			
			 q = (ArrayList<Question>)MS.client.GetMessage();
		
			if(q!=NULL){
				populateTable(q);}
			else
			 noQuestionInSubject();// there are no questions in Subject
			
			
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
	}
	
	/**
	 * no Pending Teachers Requests
	 */
	public void noQuestionInSubject(){
		panelQuestion.removeAll();
		JLabel noPendingRequests = new JLabel("No Questions in subject");
		panelQuestion.add(noPendingRequests, BorderLayout.NORTH);
		panelQuestion.revalidate();
		panelQuestion.repaint();
		
	
	}
	
	/**
	 * this method gets an ArrayList<Question> and fills a table with all question in the subject
	 * @param myArrayq2 
	 * @param confirmationAL
	 */
	public void populateTableTest(ArrayList<Question> myArrayq2) {
		
		Vector<String> columnNames = new Vector<String>();
		Vector<Vector<Object>> tableModel2 = new Vector<Vector<Object>>();
		
		columnNames.addElement("#");
		columnNames.addElement("Question ID");
		columnNames.addElement("Question");
		columnNames.addElement("Correct Answer");
		columnNames.addElement("Points");
		columnNames.addElement("Instructions");

		
		// create new Submission list to show to the teacher
		Vector<Object> row;	
		for (int i=0; i <myArrayq2.size() ; i++){
			row = new Vector<Object>(5);
			row.addElement(i+1);// auto increment number
			row.addElement(myArrayq2.get(i).getQuestionID());		
			row.addElement(myArrayq2.get(i).getQuestion());
			row.addElement ((myArrayq2.get(i).getCorrectAnswer()));
			row.addElement( myArrayt.get(i).getPointQuestion());
			row.addElement(myArrayq2.get(i).getQuestionCommet());
			rowInTable++;
			tableModel2.addElement(row);
		}
		if (scrollPaneTable != null)
			scrollPaneTable.removeAll();
		panelTest.removeAll();
		
		testTabel= new JTable(tableModel2, columnNames);
		testTabel = new JTable(tableModel2, columnNames){
			   public boolean isCellEditable(int rowIndex, int colIndex) {
			   return false; //Disallow the editing of any cell
			   }};
		scrollPaneTable = new JScrollPane(testTabel);
        testTabel.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        TableColumn columnCorrect=testTabel.getColumnModel().getColumn(5);
		columnCorrect.setPreferredWidth(WIDTH*150);
		TableColumn columnCorrec=testTabel.getColumnModel().getColumn(2);
		columnCorrec.setPreferredWidth(WIDTH*150);
		TableColumn columnCorre=testTabel.getColumnModel().getColumn(3);
		columnCorre.setPreferredWidth(WIDTH*100);
        testTabel.getTableHeader().setReorderingAllowed(false);
        testTabel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        testTabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		JScrollPane scrollPane= new JScrollPane(testTabel);
		panelTest.add(scrollPane);
		testTabel.setName("Questions in Test");
		panelTest.setVisible(true);
	    this.validate();
		 this.repaint();

			scrollPaneTable.setVisible(true);
			calculatepoints();
			
	}//end populateTableTest
	
	
	
	/**
	 * Adds a new question to test table by the selection of User 
	 */
	public void JoinQuestionToTable(int selectedRow){
		
			
			if (checkInut()==true){
			Question questionSelected =q.get(selectedRow); //get Question that was choosen
			if(rowInTable==0){
				myArrayq =new ArrayList<sharedspace.Question> ();
				myArrayq.add(questionSelected);
				rowInTable++;
				saveQuestionIntest(questionSelected);
				populateTableTest(myArrayq);
			}else{
				if (alreadyInTest(questionSelected)==false){
				myArrayq.add(questionSelected);
				
			saveQuestionIntest(questionSelected);
			populateTableTest(myArrayq);
			calculatepoints();
				}else
					showMessage("Error question alreay in test", "In test error", JOptionPane.WARNING_MESSAGE);
			}//end else
			}//end if  		
	}// end JoinQuestionToTable
	
	/**
	 * Removes a question from test table by the selection of User 
	 */
	public void RemoveQuestionFromTable(int selectedRow){
		
			
			 //get Question that was chosen
			if(myArrayq.size()>0){	
				myArrayq.remove(myArrayq.get(selectedRow));
				populateTableTest(myArrayq);
				myArrayt.remove(myArrayt.get(selectedRow));
				calculatepoints();
			}else
				
				showMessage("Error no more question", "no more questions in test", JOptionPane.WARNING_MESSAGE);
		    
			}   		

	public void ClearComment() {
	
		txtCommentStudent.setText("");
		txtCommentTeacher.setText("");
		
	}//end ClearComment   
	
	public void showMessage(String message, String title, int messageType) {
		JOptionPane.showMessageDialog(this, message,title,messageType);		
	}	  

	
	public void saveQuestionIntest(Question questionSelected){
		
		QuestionInTest qTest = new QuestionInTest();
		int point = Integer.parseInt(txtPoints.getText());
		txtPoints.setText("");
		if(rowInTable<=1){
			myArrayt =new ArrayList<sharedspace.QuestionInTest> ();
			qTest.setQuestion(questionSelected);
			qTest.setPointQuestion(point);
			createTheTestdummy();
			qTest.setTest(testDummy);
			myArrayt.add(qTest);
		}else{
		qTest.setPointQuestion(point);
		qTest.setQuestion(questionSelected);
		myArrayt.add(qTest);
		qTest.setTest(testDummy);}
	}// end saveQuestionIntest
	
	public void createTheTestdummy(){
		testDummy=new Test();
		Teacher teacher = new Teacher(user);
		testDummy.setAuthor(teacher);
		testDummy.setCommentForStudent(txtCommentStudent.getText());
		testDummy.setCommentForTeacher(txtCommentTeacher.getText());
		testDummy.setTestDuration(1);
		testDummy.setTestID("1");
		testDummy.setSubject(subject);
	}
	
	public void createTheTest(){
		test=testDummy;
		test.setCommentForStudent(txtCommentStudent.getText());
		test.setCommentForTeacher(txtCommentTeacher.getText());
		MessageAllocateTestId qTt = new MessageAllocateTestId(subjectID,courseID,test);
		try{
			MS.client.sendToServer(qTt);// get list of teacher subject
			 String testID = (String)MS.client.GetMessage();
			 test.setTestID(testID);
			}
			catch (Exception e) {
				System.err.println("Can't get testID");
			}
		
		saveQuestionsInTest();
		
	
		
	}//end createTheTest
	
/**
 *  insert question in test to DB
 *  and update it to use	
 */
	public void saveQuestionsInTest()
	{
		for (int i=0;i<myArrayt.size();i++)
		{
			myArrayt.get(i).setTest(test);
			MessageSaveQuestionsTest qIt = new MessageSaveQuestionsTest(myArrayt.get(i));
			try{
				MS.client.sendToServer(qIt);// get list of teacher subject
				 //MS.client.GetMessage();
				}
				catch (Exception e) {
					System.err.println("Can't allocate Question");
				}
		}//end for
		
		
			
	}//end saveQuestionsInTest
	
	/**
	 * check to if question already in test
	 * @param Question
	 * @return Boolean
	 */
	public Boolean alreadyInTest(Question questioncheck)
	{
		for(int i=0;i<myArrayt.size();i++)
		{
			if (questioncheck.getQuestionID()==myArrayt.get(i).getQuestion().getQuestionID())
				return true;
		}
		return false;
	}

	public void calculatepoints(){
		
		int TotalPoints=0;
		
		for(int i=0;i<myArrayt.size();i++)
		{
		 TotalPoints+=myArrayt.get(i).getPointQuestion();	
				
		}//end for
		
		totalPoints.setText(""+TotalPoints);
	}//end calculatepoints
	
	/**
	 * This function checks if  there are no errors in question input
	 * @return Boolean
	 */
	public Boolean checkInut(){
		int point;
		try
		{
			point = Integer.parseInt(txtPoints.getText());
			if (point >100 || point <1){
				showMessage("Error, you need to fill out a number between 1 and 100", "Insert point as number", JOptionPane.WARNING_MESSAGE);
				return false;
			}
		}// end try
		catch(Exception e)
		{
			showMessage("Error, you need to fill points", "Insert point as number", JOptionPane.WARNING_MESSAGE);
			return false;
		}// end catch
	
	return true;
	}// end checkInut
	public boolean cheackDuration(String duration)
	{
		try
		{
			int minutes = Integer.parseInt(duration);
			if (minutes>0)
			{
				testDummy.setTestDuration(minutes);
			return true;
			}
			
		}
		catch (NullPointerException e)
		{
			return false;
		}
		catch(NumberFormatException e)
		{
			return false;
		}
		return false;
	}
	public Test getTest() {
		return test;
	}

	public void setTest(Test test) {
		this.test = test;
	}

	public Test getTestDummy() {
		return testDummy;
	}

	public void setTestDummy(Test testDummy) {
		this.testDummy = testDummy;
	}
}//end GUI_CreateText



